package validator

import (
	"reflect"

	V "gitee.com/go-spring2/spring-core/validate"
	CN_ZH "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

var Trans ut.Translator

func init() {
	zh := CN_ZH.New()
	uni := ut.New(zh, zh)
	Trans, _ = uni.GetTranslator("zh")

	validate := validator.New()
	//通过label标签返回自定义谬误内容
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("json")
		if label == "" {
			return field.Name
		}
		return label
	})

	zhTranslations.RegisterDefaultTranslations(validate, Trans)

	V.Validator = &Validate{
		v: validate,
	}
}

type Validate struct {
	v *validator.Validate
}

func (v *Validate) TagName() string {
	return "validate"
}

func (v *Validate) Struct(i interface{}) error {
	return v.v.Struct(i)
}

func (v *Validate) Field(i interface{}, tag string) error {
	return v.v.Var(i, tag)
}
